import {makeAutoObservable, observable} from 'mobx'
import {apiDomain, postData} from "./api";
import {Modal, Toast} from "@ant-design/react-native";

interface CartItem {
    info: Object
    num: number,
    id: number
}

class CartStatus {
    cartList: CartItem[] = []
    cartSum: number = 0
    promotion: number = 0
    promotionCode: string = ""

    constructor() {
        makeAutoObservable(this)
    }

    setUserStatus = (list) => {
        this.cartList = list
    }

    setPromotion = (promotion: number) => {
        this.promotion = promotion
    }

    setPromotionCode = (promotionCode: string) => {
        this.promotionCode = promotionCode
    }

    addToList = (item: CartItem) => {
        let find = false
        this.cartList.map(i => {
            if (item.id === i.id) {
                i.num = i.num + 1
                find = true
            }
        })
        if (!find) {
            this.cartList.push(item)
        }
        this.calcSum()
    }

    calcSum = () => {
        if (this.cartList.length === 0) {
            this.cartSum = 0
            return
        }
        const data = this.cartList.map(o => {
            return {
                count: o.num,
                id: o.info['id']
            }
        })
        postData(apiDomain + "/Index/getCartSum", {list: data}).then(res => {
            if (res.code === 200) {
                console.log('calc sum success', res.data)
                if (this.promotion === 0) {
                    this.cartSum = res.data.sum
                } else {
                    this.cartSum = parseFloat((res.data.sum * (100 - this.promotion) / 100).toFixed(2))
                }
            } else {
                Modal.alert('Error', res.msg, [
                    {text: 'OK'},
                ])
            }
        })
    }
}

const cartStatus = new CartStatus()
export default cartStatus
